<template>
  <el-row>
    <div v-for="node in $store.getters['WORKFLOW/tree']" :key="node.workflowNodeVo.bpmnNodeId">
      <workflow-node :node="node"
                     :search="search"
                     :auditor="auditor"
                     @node-delete="nodeDelete"
                     @node-open="dialogOpen"></workflow-node>
    </div>
    <s-dialog :dialog="dialog">
      <p slot="title">{{dialog.title}}流程节点 <span
        v-if="dialog.title === '修改'">节点名称：{{dialog.row.workflowNodeVo.workFlowNodeName}}</span></p>
      <el-collapse :value="['1', '2', '3']" class="workflowCollapse">
        <s-form :form="formDialog" ref="formDialog">
          <el-collapse-item title="基础信息" v-if="!auditor && !(dialog.title === '修改' && dialog.row.workflowNodeVo.bpmnNodeId === 'start_user_task_id')" name="1">
            <el-row>
              <el-col :xs="24" :lg="{span: 7, offset: 0}" class="">
                <el-form-item prop="workFlowNodeName" label="节点名称">
                  <el-input
                    type="text"
                    :disabled="dialog.title === '修改' && (dialog.row.workflowNodeVo.bpmnNodeId === 'end_event_id' || dialog.row.workflowNodeVo.bpmnNodeId === 'start_user_task_id')"
                    v-model="formDialog.workFlowNodeName"
                    placeholder="节点名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 7, offset: 1}" class="">
                <el-form-item prop="auditorType" label="审核人类型">
                  <el-select filterable
                             ref="auditorType"
                             v-model="formDialog.auditorType"
                             placeholder="请选择">
                    <el-option
                      v-for="item in WORKFLOW.workflowAuditorType"
                      :key="item.id"
                      :label="item.text"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 7, offset: 1}" class="">
                <el-form-item label="是否具有驳回权限">
                  <el-switch
                    v-model="formDialog.type"
                    active-text="是"
                    inactive-text="否"
                    :active-value="1"
                    :inactive-value="2"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="节点条件" v-if="!auditor" name="2">
            <el-row style="position: relative">
              <el-button type="primary" round size="mini"
                         @click="dialogBranchOpen"
                         icon="el-icon-plus"
                         class="add-details-button">添加条件</el-button>
            </el-row>
            <el-row v-for="(branch, index) in formDialog.workflowBranchDetailVos" :key="index">
              <el-col :xs="24" :lg="{span: 23, offset: 0}">
                <workflow-node-next
                  class="add-node-next"
                  :branch="branch"
                  :node="$store.getters['WORKFLOW/tree'][branch.workflowBranchVo.toBranch]"></workflow-node-next>
                <el-button type="danger"
                           v-if="index !== 0"
                           style="margin-left: 5px"
                           round
                           @click="deleteBranch(index)"
                           size="mini"
                           icon="el-icon-delete"></el-button>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="审核人" name="3" v-if="!(dialog.title === '修改' && dialog.row.workflowNodeVo.bpmnNodeId === 'start_user_task_id')">
            <el-row>
              <el-col :xs="24" :lg="{span: 7, offset: 0}" class="">
                <el-form-item label="查询审核人">
                  <el-input v-model="dialog.searchAudior"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 3, offset: 1}" class="">
                <el-form-item prop="workflowAudiorVo" label="操作">
                  <div class="s-content">
                    <el-button type="primary"
                               round
                               icon="el-icon-search"
                               size="mini"
                               @click="searchAudior"></el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 11, offset: 1}" class="">
                <el-form-item prop="workflowAudiorVo" label="已经选择的审核人">
                  <el-select
                    filterable
                    multiple
                    ref="workflowAudiorVo"
                    :remote-method="userList"
                    v-model="formDialog.workflowAudiorVo"
                    placeholder="请选择">
                    <el-option
                      v-for="item in dialog.userList"
                      :key="item.id"
                      :label="item.name + '   ' + item.orgName + '   ' + item.userAccount"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </s-form>
      </el-collapse>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogBranch">
      <p slot="title">新增节点条件</p>
      <s-form :form="formDialogBranch" ref="formDialogBranch">
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}" class="">
            <el-form-item prop="branckName" label="条件名称">
              <el-input
                type="text"
                v-model="formDialogBranch.branckName"
                placeholder="条件名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}" class="">
            <el-form-item prop="toBranch" label="下一节点">
              <el-select filterable
                         ref="auditorType"
                         v-model="formDialogBranch.toBranch"
                         placeholder="请选择">
                <el-option
                  v-for="item in toBranch"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 7, offset: 0}" class="">
            <el-form-item prop="formDetailId" label="字段">
              <el-select filterable
                         ref="formDetailId"
                         v-model="formDialogBranch.formDetailId"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.formDetailId"
                  :key="item.id"
                  :label="item.showAttributeName + '   ' + item.attributeName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 7, offset: 1}" class="">
            <el-form-item prop="type" label="方法">
              <el-select filterable
                         ref="type"
                         v-model="formDialogBranch.type"
                         placeholder="请选择">
                <el-option
                  v-for="item in WORKFLOW.workflowConditionType"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 7, offset: 1}" class="">
            <el-form-item prop="workflowExpression" label="值">
              <el-input
                type="text"
                v-model="formDialogBranch.workflowExpression"
                placeholder="值"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogBranchSave">保存</el-button>
    </s-dialog>
  </el-row>
</template>

<script>
  import {AutoVue, AutoPromise, DeepCopy} from '~/plugins/Tools';
  import WorkflowNode from './workflowNode.vue';
  import WorkflowNodeNext from './workflowNodeNext.vue';
  let nodeId = new Date().getTime();

  function start_event_id () {
    return {
      bpmnNodeId: 'start_event_id',
      branckName: '默认条件',
      isDefault: 2,
      remark: '审核通过后执行下一个流程',
      toBranch: 'end_event_id',
    };
  }
  function workflowNode () {
    return {
      bpmnNodeId: { value: '', rule: [] },
      fatherNodeId: { value: '', rule: [] },
      nextNodeId: { value: '', rule: [] },
      nodeLeave: { value: '', rule: [] },
      auditorType: { value: '', rule: ['vNull__change'] },
      type: { value: 1, rule: [] }, // 有无驳回
      workFlowNodeName: { value: '', rule: ['vNull'] },

      workflowAudiorVo: { value: [], rule: ['vNull__change'] },
      workflowBranchDetailVos: {
        value: [
          {
            workflowBranchDetailVos: [],
            workflowBranchVo: start_event_id(),
          },
        ],
        rule: [] },
    };
  }
  function workFlowBranchPojoList_workflowBranchDetailVos () {
    return {
      formDetailId: { value: '', rule: ['vNull__change'] },
      type: { value: '', rule: ['vNull__change'] },
      workflowExpression: { value: '', rule: ['vNull'] },
      toBranch: { value: 'end_event_id', rule: ['vNull'] },
      branckName: { value: '', rule: ['vNull'] },
    };
  }

  export default AutoVue({
    name: 'workflow',
    data: {
      dialog: {
        row: {
          workflowNodeVo: {},
        },
        formDetailId: [],
        userList: [],
        title: '新增',
        isPorp: 'formDialog',
        dialogCallBack: function () {
          this.formDialog.workflowBranchDetailVos = [{
            workflowBranchDetailVos: [],
            workflowBranchVo: start_event_id(),
          }];
        },
        searchAudior: '',
        modal: false,
      },
      formDialog: workflowNode(),

      dialogBranch: {
        modal: false,
        isPorp: 'formDialogBranch',
      },
      formDialogBranch: workFlowBranchPojoList_workflowBranchDetailVos(),
    },
    props: {
      pojos: {
        type: Array,
        default: function () {
          return [];
        },
      },
      form: {
        type: Object,
        required: true,
      },
      auditor: {
        type: Boolean,
        default: false,
      },
      search: {
        type: Boolean,
        default: false,
      },
    },
    store: ['WORKFLOW', 'DICTIONARY_workflow'],
    computed: {
      toBranch: function () {
        if (!this.dialog.row.workflowNodeVo) return [];
        const parentId = this.dialog.row.workflowNodeVo.bpmnNodeId;
        let flag = false;
        let step = [];
        this.WORKFLOW.data.forEach((item, index) => {
          if (flag) {
            step.push({
              id: item.workflowNodeVo.bpmnNodeId,
              name: item.workflowNodeVo.workFlowNodeName,
            });
          }
          if (item.workflowNodeVo.bpmnNodeId === parentId) {
            flag = true;
          }
        });
        return step;
      },
    },
    components: {
      workflowNode: WorkflowNode,
      workflowNodeNext: WorkflowNodeNext,
    },
    watch: {},
    methods: {
      async userList (query) {
        let {contentList} = await this.post('/workflowConfig/userList', {
          name: query,
        });
        this.dialog.userList = contentList;
        return contentList;
      },

      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        this.dialog.row = DeepCopy(more);
        let autoPromise = [
          async () => {
            if (!this.auditor) {
              let {contentList} = await this.get('/form/formDetails/' + this.form.formId);
              this.dialog.formDetailId = contentList;
            }
          },
        ];
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.bpmnNodeId = 's' + (nodeId++) + '';
          autoPromise.push(async () => {
            this.userList('');
          });
          break;
        case 'PUT':
          this.dialog.title = '修改';
          this.$nextTick(() => {
            this.formDialog = {
              ...this.formDialog,
              ...this.ObjectClone(workflowNode(), more.workflowNodeVo),
            };
            let audiors = [];
            let userList = [];
            let json = DeepCopy(more.workflowAudiorVo);
            json.forEach(item => {
              userList.push({
                id: item.userId,
                name: item.show_userId,
              });
              audiors.push(item.userId);
            });
            this.dialog.userList = userList;
            this.formDialog.workflowAudiorVo = audiors;
            this.formDialog.workflowBranchDetailVos = DeepCopy(more.workFlowBranchPojoList);
          });
          break;
        }
        await AutoPromise(autoPromise);
        this.dialog.visible = true;
      },
      async searchAudior () {
        let {contentList} = await this.post('/workflowConfig/userList', {
          name: this.dialog.searchAudior,
        });
        this.dialog.userList = contentList;
      },
      dialogSave () {
        this.VALIDATE('formDialog', option => {
          let audiors = [];
          if (option.workflowAudiorVo) {
            option.workflowAudiorVo.forEach((item, index) => {
              audiors.push({
                userId: item,
                show_userId: this.$refs.workflowAudiorVo.selected[index].currentLabel,
              });
            });
          }
          let json = {
            workFlowBranchPojoList: DeepCopy(option.workflowBranchDetailVos),
            workflowAudiorVo: audiors,
          };
          delete option.workflowAudiorVo;
          delete option.workflowBranchDetailVos;
          if (!this.auditor) {
            if (this.$refs.auditorType) {
              option.show_auditorType = this.$refs.auditorType.selectedLabel;
            }
            json.workflowNodeVo = option;
          } else {
            json.workflowNodeVo = this.dialog.row.workflowNodeVo;
          }
          json.workFlowBranchPojoList[0].workflowBranchVo.bpmnNodeId = json.workflowNodeVo.bpmnNodeId;
          if (this.dialog.title === '新增') {
            this.SET('WORKFLOW_data', {
              node: json,
              parentNode: this.dialog.row,
            });
          } else {
            this.PUT('WORKFLOW_data', json);
          }
          this.dialog.dialogInit.call(this);
        });
      },

      dialogBranchOpen () {
        this.dialogBranch.visible = true;
      },
      dialogBranchSave () {
        this.VALIDATE('formDialogBranch', option => {
          this.formDialog.workflowBranchDetailVos.push({
            workflowBranchDetailVos: [
              {
                formDetailId: option.formDetailId,
                show_formDetailId: this.$refs.formDetailId.selectedLabel,
                type: option.type,
                show_type: this.$refs.type.selectedLabel,
                workflowExpression: option.workflowExpression,
              },
            ],
            workflowBranchVo: {
              bpmnNodeId: this.formDialog.bpmnNodeId,
              branckName: option.branckName,
              isDefault: 1,
              remark: '审核通过后执行下一个流程',
              toBranch: option.toBranch,
            },
          });
          this.dialogBranch.dialogInit.call(this);
        });
      },

      nodeDelete (node) {
        this.DEL('WORKFLOW_node', node);
      },
      deleteBranch (index) {
        this.formDialog.workflowBranchDetailVos.splice(index, 1);
      },
    },
    mounted: function () {
      console.log(this);
      if (this.obj) {
      }
    },
  });
</script>

<style lang="scss">
  .workflowCollapse .el-collapse-item__content{
    padding: 0 20px 25px;
  }
  .add-node-next{
    text-align: left !important;
    margin: 10px 0;
    display: inline-block;
  }
  .add-details-button {
    position: absolute;
    right: 20px;
    z-index: 100;
  }
  @media screen and (max-width: 800px) {
  }
</style>
